<template>
    <div class="extract-page">
        <el-card>
            <template #header>
                <div class="card-header">
                    <h3>知识抽取</h3>
                    <el-tag type="info" size="large">基于领域词典增强的知识抽取</el-tag>
                </div>
            </template>

            <el-row :gutter="24">
                <el-col :span="16">
                    <el-form :model="form" label-width="120px">
                        <!-- 选择文档 -->
                        <el-form-item label="选择文档" required>
                            <el-select v-model="form.selectedDocId" placeholder="请选择要抽取的文档" style="width: 100%"
                                filterable @change="onDocumentChange">
                                <el-option v-for="doc in availableDocuments" :key="doc.id" :label="doc.title"
                                    :value="doc.id">
                                    <div style="line-height: 1.4">
                                        <div style="font-weight: bold">{{ doc.title }}</div>
                                        <div style="font-size: 12px; color: #8492a6">
                                            {{ doc.summary }}
                                        </div>
                                    </div>
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <!-- 预览选中的文档 -->
                        <el-form-item label="文档内容" v-if="selectedDocument && selectedDocument.content">
                            <el-input :value="selectedDocument.content" type="textarea" :rows="8" readonly
                                style="background-color: #f5f7fa" />
                        </el-form-item>

                        <!-- 自定义提示词 -->
                        <el-form-item label="抽取提示词" required>
                            <div class="prompt-container">
                                <el-input v-model="form.prompt" type="textarea" :rows="10" placeholder="描述您想从文档中抽取什么信息，例如：锅炉爆管的原因和处理方法" />
                                <div class="prompt-actions">
                                    <el-button type="primary" :icon="MagicStick" @click="optimizePrompt"
                                        :loading="optimizing" size="small">
                                        AI优化提示词
                                    </el-button>
                                </div>
                            </div>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" @click="handleExtract" :loading="loading"
                                :disabled="!form.prompt || !form.selectedDocId" size="large">
                                <el-icon>
                                    <Cpu />
                                </el-icon>
                                开始抽取
                            </el-button>
                            <el-button @click="handleClear" size="large">清空</el-button>
                        </el-form-item>
                    </el-form>

                    <!-- 抽取结果 -->
                    <div v-if="result" class="result-section">
                        <el-divider content-position="left">
                            <h3>抽取结果</h3>
                        </el-divider>

                        <!-- 实体 -->
                        <div class="entities-section">
                            <h4>🏷️ 抽取的实体：</h4>
                            <el-row :gutter="15">
                                <el-col :span="12" v-for="(values, type) in result.data.entities" :key="type">
                                    <div class="entity-group">
                                        <div class="entity-type">{{ type }}</div>
                                        <div class="entity-tags">
                                            <el-tag v-for="(value, idx) in values" :key="idx" class="entity-tag"
                                                effect="light">
                                                {{ value }}
                                            </el-tag>
                                            <el-empty v-if="values.length === 0" description="未找到该类型实体"
                                                :image-size="60" />
                                        </div>
                                    </div>
                                </el-col>
                            </el-row>
                        </div>

                        <!-- 关系 -->
                        <div class="relations-section">
                            <h4>🔗 抽取的关系：</h4>
                            <el-table :data="result.data.relations" border stripe>
                                <el-table-column prop="subject" label="主体" width="200" />
                                <el-table-column prop="predicate" label="关系" width="150">
                                    <template #default="{ row }">
                                        <el-tag type="success">{{ row.predicate }}</el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="object" label="客体" />
                            </el-table>
                        </div>
                    </div>
                </el-col>

                <!-- 分隔线 -->
                <el-col :span="1" class="divider-col">
                    <div class="vertical-divider"></div>
                </el-col>

                <!-- 历史记录 -->
                <el-col :span="7">
                    <div class="history-section">
                        <h4>历史记录</h4>
                        <el-timeline>
                            <el-timeline-item v-for="item in historyList" :key="item.id"
                                :timestamp="formatTime(item.created_at)" placement="top">
                                <el-card class="history-card" @click="viewHistoryItem(item)">
                                    <div class="history-content">
                                        <div class="history-prompt">
                                            <el-icon style="margin-right: 4px;">
                                                <View />
                                            </el-icon>
                                            {{ item.prompt ? item.prompt.substring(0, 50) + '...' : '知识抽取' }}
                                        </div>
                                        <div class="history-doc">{{ item.document.substring(0, 50) }}...</div>
                                        <div class="history-hint">点击查看详情</div>
                                    </div>
                                </el-card>
                            </el-timeline-item>
                        </el-timeline>
                    </div>
                </el-col>
            </el-row>
        </el-card>

    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Cpu, View, MagicStick } from '@element-plus/icons-vue'
import api from '../api'

// 数据
const form = ref({
    prompt: '',
    selectedDocId: null
})

const availableDocuments = ref([])
const selectedDocument = computed(() => {
    return availableDocuments.value.find(doc => doc.id === form.value.selectedDocId)
})

const loading = ref(false)
const optimizing = ref(false)
const result = ref(null)
const historyList = ref([])

// 加载可用文档列表（从文档管理加载）
const loadDocuments = async () => {
    try {
        const response = await api.get('/documents')
        if (response.success) {
            availableDocuments.value = response.documents.map(doc => ({
                ...doc,
                summary: `${doc.filename} (${formatFileSize(doc.file_size)})`,
                content: ''
            }))
        }
    } catch (error) {
        console.error('加载文档列表失败:', error)
        ElMessage.error('加载文档列表失败')
    }
}

// 格式化文件大小
const formatFileSize = (bytes) => {
    if (!bytes) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

// 文档选择变化 - 加载完整内容
const onDocumentChange = async () => {
    result.value = null

    if (form.value.selectedDocId) {
        try {
            const response = await api.get(`/documents/${form.value.selectedDocId}`)
            if (response.success) {
                const index = availableDocuments.value.findIndex(doc => doc.id === form.value.selectedDocId)
                if (index !== -1) {
                    availableDocuments.value[index].content = response.content
                }
            }
        } catch (error) {
            console.error('加载文档内容失败:', error)
            ElMessage.error('加载文档内容失败')
        }
    }
}

// 优化提示词
const optimizePrompt = async () => {
  if (!form.value.prompt) {
    ElMessage.warning('请先输入提示词')
    return
  }

  optimizing.value = true

  try {
    const response = await api.post('/extract/optimize-prompt', {
      prompt: form.value.prompt
    })

    if (response.success) {
      form.value.prompt = response.optimized_prompt
      ElMessage.success('提示词已优化！')
    } else {
      ElMessage.error(response.message || '优化失败')
    }
  } catch (error) {
    console.error('优化提示词失败:', error)
    ElMessage.error('优化失败：' + (error.response?.message || error.message))
  } finally {
    optimizing.value = false
  }
}

// 执行抽取
const handleExtract = async () => {
    if (!form.value.prompt || !form.value.selectedDocId) {
        ElMessage.warning('请输入提示词并选择文档')
        return
    }

    loading.value = true
    result.value = null

    try {
        const response = await api.post('/extract', {
            prompt: form.value.prompt,
            document_id: form.value.selectedDocId
        })

        if (response.success) {
            result.value = response
            ElMessage.success('抽取成功！')
            loadHistory()
        } else {
            ElMessage.error(response.message || '抽取失败')
        }
    } catch (error) {
        console.error('抽取失败:', error)
        ElMessage.error('抽取失败：' + (error.response?.message || error.message))
    } finally {
        loading.value = false
    }
}

// 清空表单
const handleClear = () => {
    form.value = {
        prompt: '',
        selectedDocId: null
    }
    result.value = null
}

// 加载历史记录列表
const loadHistory = async () => {
    try {
        const response = await api.get('/extractions')
        if (response.success) {
            historyList.value = response.extractions
        }
    } catch (error) {
        console.error('加载历史记录失败:', error)
    }
}

// 查看历史记录详情
const viewHistoryItem = async (item) => {
    try {
        const response = await api.get(`/extractions/${item.id}`)

        if (response.success) {
            const extractionResult = JSON.parse(response.extraction.result)

            result.value = {
                data: extractionResult
            }

            form.value.prompt = response.extraction.prompt

            ElMessage.success('已加载历史记录')
        } else {
            ElMessage.error('加载历史记录失败')
        }
    } catch (error) {
        console.error('加载历史记录失败:', error)
        ElMessage.error('加载历史记录失败：' + (error.response?.message || error.message))
    }
}

// 格式化时间
const formatTime = (timeStr) => {
    const date = new Date(timeStr)
    return date.toLocaleString('zh-CN')
}

onMounted(() => {
    loadDocuments()
    loadHistory()
})
</script>

<style scoped>
.extract-page {
    padding: 0;
    width: 100%;
    max-width: 100%;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0;
}

.card-header h3 {
    margin: 0;
    font-family: var(--font-family);
    font-size: var(--font-size-xl);
    font-weight: 500;
    color: var(--text-primary);
}

.prompt-container {
    width: 100%;
}

.prompt-actions {
    display: flex;
    gap: var(--spacing-sm);
    margin-top: var(--spacing-md);
}

.result-section {
    margin-top: var(--spacing-2xl);
    padding-top: var(--spacing-2xl);
    border-top: 2px solid var(--border-lighter);
}

.entities-section {
    margin-bottom: var(--spacing-2xl);
}

.entities-section h4 {
    margin-bottom: var(--spacing-lg);
    color: var(--success-color);
    font-family: var(--font-family);
    font-weight: 500;
    font-size: var(--font-size-lg);
}

.entity-group {
    background: var(--bg-secondary);
    padding: var(--spacing-lg);
    border-radius: var(--radius-lg);
    margin-bottom: var(--spacing-lg);
    min-height: 120px;
}

.entity-type {
    font-weight: 500;
    color: var(--text-primary);
    margin-bottom: var(--spacing-md);
    font-size: var(--font-size-md);
    font-family: var(--font-family);
}

.entity-tags {
    display: flex;
    flex-wrap: wrap;
    gap: var(--spacing-sm);
}

.entity-tag {
    margin: 0;
    border-radius: var(--radius-sm);
    font-family: var(--font-family);
}

.relations-section h4 {
    margin-bottom: var(--spacing-lg);
    color: var(--warning-color);
    font-family: var(--font-family);
    font-weight: 500;
    font-size: var(--font-size-lg);
}

.divider-col {
    display: flex;
    justify-content: center;
    padding: 0 !important;
}

.vertical-divider {
    width: 1px;
    height: 100%;
    min-height: 500px;
    background: linear-gradient(to bottom,
            transparent 0%,
            var(--border-lighter) 10%,
            var(--border-light) 50%,
            var(--border-lighter) 90%,
            transparent 100%);
}

.history-section {
    position: sticky;
    top: 24px;
    max-height: calc(100vh - 200px);
    overflow-y: auto;
    padding-right: 8px;
}

.history-section::-webkit-scrollbar {
    width: 4px;
}

.history-section::-webkit-scrollbar-track {
    background: transparent;
}

.history-section::-webkit-scrollbar-thumb {
    background: var(--border-light);
    border-radius: 4px;
}

.history-section h4 {
    margin-bottom: var(--spacing-lg);
    margin-top: 0;
    font-family: var(--font-family);
    font-weight: 500;
    font-size: var(--font-size-lg);
    color: var(--text-primary);
    position: sticky;
    top: 0;
    background: var(--bg-primary);
    padding: var(--spacing-md) 0;
    z-index: 1;
    border-bottom: 1px solid var(--border-lighter);
}

.history-card {
    cursor: pointer;
    border-radius: var(--radius-lg);
    margin-bottom: var(--spacing-md);
    transition: border-color 0.2s ease;
}

.history-card:hover {
    border-color: var(--primary-blue);
}

.history-content {
    font-size: var(--font-size-xs);
    font-family: var(--font-family);
}

.history-prompt {
    font-weight: 500;
    margin-bottom: var(--spacing-sm);
    color: var(--primary-blue);
    font-family: var(--font-family);
    display: flex;
    align-items: center;
}

.history-doc {
    color: var(--text-secondary);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-family: var(--font-family);
}

.history-hint {
    margin-top: var(--spacing-sm);
    font-size: var(--font-size-xs);
    color: var(--primary-blue);
    opacity: 0;
    transition: opacity 0.2s ease;
    font-family: var(--font-family);
}

.history-card:hover .history-hint {
    opacity: 1;
}

:deep(.el-card) {
    border-radius: var(--radius-lg) !important;
    box-shadow: var(--shadow-sm) !important;
}

:deep(.el-card__body) {
    padding: var(--spacing-2xl) !important;
}

:deep(.el-form-item) {
    margin-bottom: var(--spacing-xl);
}

:deep(.el-select-dropdown__item) {
    height: auto;
    padding: var(--spacing-md) var(--spacing-lg);
    line-height: var(--line-height-relaxed);
    font-family: var(--font-family);
}

:deep(.el-form-item__label) {
    font-family: var(--font-family);
    font-weight: 500;
    color: var(--text-primary);
}

:deep(.el-button) {
    font-family: var(--font-family);
}
</style>
